<template>
	<view class="container">
		<!-- 1. 顶部：配送方式选择 + 店铺/自提点信息 -->
		<view class="co-top">
			<!-- 配送方式切换（自提点/到店自提） -->
			<view class="nav u-flex u-col-center u-row-between">
				<view class="i" :class="{on1: type == 1}" @click="changeType(1)">
					自提点
				</view>
				<view class="i" :class="{on2: type == 2}" @click="changeType(2)">
					到店自提
				</view>
			</view>

			<!-- 自提点信息（类型1） -->
			<view class="shop u-flex u-col-center u-row-between" v-if="type == 1"
				@click="$pageTo('/pages/index/changeMode')">
				<view class="l u-flex u-col-center u-row-between">
					<view class="img">
						<image src="@/static/image/shop.png" mode="aspectFill"></image>
					</view>
					<view class="con">
						<view class="name u-l-1">{{sendData.name}}</view>
						<view class="p">{{sendData.address}}</view>
						<view class="p" v-if="sendData.distance">距您{{sendData.distance.toFixed(2)}}km</view>
					</view>
				</view>
				<view class="r">
					<image src="@/static/image/of6.png" mode="aspectFill"></image>
				</view>
			</view>

			<!-- 到店自提信息（类型2） -->
			<view class="shop u-flex u-col-center u-row-between" v-if="type == 2">
				<view class="l u-flex u-col-center u-row-between">
					<view class="img">
						<image src="@/static/image/shop.png" mode="aspectFill"></image>
					</view>
					<view class="con">
						<view class="name u-l-1">{{shopData.name}}</view>
						<view class="p">{{shopData.address}}</view>
						<view class="p" v-if="shopData.distance">距您{{shopData.distance.toFixed(2)}}km</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 2. 中间：订单商品列表 -->
		<view class="list">
			<view class="item" v-for="(item, index) in list" :key="index">
				<!-- 日期和取餐时间 -->
				<view class="i-top">
					<image src="../../static/image/of5.png" mode="aspectFill"></image>
					<text class="t1">{{getDay(item.upday)}} {{getDay3(item.uptime)}}</text>
					<text class="t2">可取餐</text>
				</view>

				<!-- 商品列表 -->
				<view class="i-list">
					<view class="i-middle u-flex u-col-top u-row-between" v-for="(item2, index2) in item.list"
						:key="index2">
						<view class="img">
							<image :src="http + item2.goods_data.dish.image" mode="aspectFill"></image>
						</view>
						<view class="con">
							<view class="name">{{item2.goods_data.dish.name}}</view>
							<!-- 规格信息（单品） -->
							<view class="info" v-if="item2.goods_data.dish.spec == 1">
								<view class="i">{{item2.spec_name}}</view>
							</view>
							<!-- 套餐信息 -->
							<view class="info" v-else>
								<view class="i" v-if="item2.goods_data.dish.type == 2">
									x1 {{item2.goods_data.dish.contain_title}}*{{item2.goods_data.dish.contain_number}}份
								</view>
								<view class="i" v-for="(item3, index3) in item2.match_dish" :key="index3">
									×{{item3.number}} {{item3.dish_name}} <text
										v-if="item3.spec_name">({{item3.spec_name}})</text>
								</view>
							</view>
						</view>
						<!-- 价格和数量 -->
						<view class="r">
							<view class="price" style="font-family:'DIN';">￥<text>{{item2.oneprice}}</text></view>
							<view class="num">×{{item2.number}}</view>
						</view>
					</view>
				</view>

				<!-- 小计 -->
				<view class="i-footer">
					小计￥<text>{{getGoodsPrice(item.list)}}</text>
				</view>
			</view>
		</view>

		<!-- 3. 底部：合计与提交订单 -->
		<view class="footer-btn u-flex u-col-center u-row-between">
			<view class="l">
				合计￥<text>{{totalPrice}}</text>
			</view>
			<view class="r" @click="$u.throttle(createOrder, 500)" v-if="can">
				<view class="t">提交订单</view>
				<view class="p">Checkout</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 状态控制
				type: 1, // 1:自提点 2:到店自提
				can: true, // 是否可提交订单

				// 数据存储
				shopData: {
					name: "",
					address: "",
					distance: 0
				}, // 店铺信息
				sendData: {
					name: "",
					address: "",
					distance: 0,
					id: ""
				}, // 自提点信息
				cList: [], // 自提点列表
				uid: "", // 用户ID
				list: [], // 按日期分组的订单商品
				arry: [], // 原始购物车数据
				totalPrice: 0, // 订单总价

				// 常量
				http: this.$imgUrl,
				longitude: "",
				latitude: ""
			};
		},

		onLoad() {
			// 初始化基础数据
			this.uid = uni.getStorageSync("uid");
			this.shopData = JSON.parse(uni.getStorageSync("shopData"));
			this.longitude = uni.getStorageSync("lng");
			this.latitude = uni.getStorageSync("lat");

			// 处理购物车数据（过滤当前店铺且日期为今天及以后的商品）
			const cartData = uni.getStorageSync("cartData") ? JSON.parse(JSON.stringify(uni.getStorageSync("cartData"))) :
				[];
			this.arry = cartData.filter(item =>
				item.shop_id == this.shopData.id &&
				this.formatYmd(new Date(item.upday)) >= this.formatYmd(new Date()) // 包含今天及以后
			);

			// 计算总价
			this.totalPrice = this.arry.reduce((acc, cur) =>
				acc + parseInt(cur.number) * parseFloat(cur.oneprice), 0
			).toFixed(2);

			// 按日期和时间分组并排序
			this.list = this.groupByUpdayAndUptime(this.arry);
			this.list.sort((a, b) => {
				if (a.upday === b.upday) return a.uptime - b.uptime;
				return new Date(a.upday) - new Date(b.upday);
			});
		},

		onShow() {
			// 获取自提点列表
			this.getlocationList();
		},

		computed: {
			// 计算单组商品总价
			getGoodsPrice() {
				return (list) => {
					return list.reduce((acc, cur) => acc + parseInt(cur.number) * parseFloat(cur.oneprice), 0).toFixed(
						2);
				};
			},

			// 格式化日期为中文描述（今天/明天/后天/MM-DD）
			getDay() {
				return (data) => {
					const today = new Date();
					const tomorrow = new Date(today);
					tomorrow.setDate(tomorrow.getDate() + 1);
					const dayAfterTomorrow = new Date(today);
					dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2);

					const format = (date) => {
						const year = date.getFullYear();
						const month = String(date.getMonth() + 1).padStart(2, "0");
						const day = String(date.getDate()).padStart(2, "0");
						return `${year}-${month}-${day}`;
					};

					if (data === format(today)) return "今天";
					if (data === format(tomorrow)) return "明天";
					if (data === format(dayAfterTomorrow)) return "后天";
					return data.substring(5);
				};
			},
			getDay3() {
				return (data) => {
					if (data == 1) {
						return '11:00前'
					}
					if (data == 2) {
						return '14:00前'
					}
					if (data == 3) {
						return '18:00前'
					}
					if (data == 4) {
						return '20:00前'
					}
				}
			}
		},

		methods: {
			// 工具方法：格式化日期为 YYYY-MM-DD（忽略时间）
			formatYmd(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, "0");
				const day = String(date.getDate()).padStart(2, "0");
				return `${year}-${month}-${day}`;
			},

			// 工具方法：按日期和时间分组
			groupByUpdayAndUptime(arr) {
				const map = {};
				arr.forEach(item => {
					const {
						upday,
						uptime,
						...rest
					} = item;
					const key = `${upday}-${uptime}`;
					if (!map[key]) map[key] = {
						upday,
						uptime,
						list: []
					};
					map[key].list.push(rest);
				});
				return Object.values(map);
			},

			// 1. 订单操作
			createOrder() {
				if (!this.uid || !this.shopData) return;
				if (this.list.length === 0) {
					uni.showToast({
						title: "不能下单",
						icon: "none"
					});
					return;
				}

				// 构建订单数据
				const orderData = this.list.map(item => {
					const goodsList = item.list.map(item2 => ({
						dish_data_id: item2.id,
						spec_name: item2.spec_name,
						number: item2.number,
						oneprice: item2.oneprice,
						price: (parseInt(item2.number) * parseFloat(item2.oneprice)).toFixed(2),
						match_dish: item2.match_dish
					}));
					return {
						price: this.getGoodsPrice(item.list),
						upday: item.upday,
						uptime: item.uptime,
						list: goodsList
					};
				});

				this.can = false; // 防止重复提交
				this.$http.post("/app/dishs/createOrder", {
					mid: this.uid,
					shop_id: this.shopData.id,
					price: this.totalPrice,
					data: JSON.stringify(orderData),
					sendtype: this.type,
					send_id: this.type === 1 ? this.sendData.id : this.shopData.id
				}).then(res => {
					if (res.code === 0) {
						// 清空当前店铺的购物车数据
						this.clearCart();
						// 发起支付
						this.handlePayment(res.data);
					} else {
						this.can = true;
						uni.showToast({
							title: res.msg,
							icon: "none"
						});
					}
				}).catch(err => {
					this.can = true;
					console.error("创建订单失败：", err);
				});
			},

			// 清空当前店铺的购物车
			clearCart() {
				const cartData = uni.getStorageSync("cartData") ? JSON.parse(JSON.stringify(uni.getStorageSync(
					"cartData"))) : [];
				const remaining = cartData.filter(item =>
					item.shop_id !== this.shopData.id ||
					this.formatYmd(new Date(item.upday)) < this.formatYmd(new Date())
				);
				if (remaining.length === 0) {
					uni.removeStorageSync("cartData");
				} else {
					uni.setStorageSync("cartData", JSON.stringify(remaining));
				}
			},

			// 处理支付
			handlePayment(payInfo) {
				const {
					appId,
					timeStamp,
					nonceStr,
					paySign,
					signType
				} = payInfo;
				const packagex = payInfo.package;
				uni.requestPayment({
					provider: "wxpay",
					appId,
					timeStamp,
					nonceStr,
					package: packagex,
					signType,
					paySign,
					success: () => {
						uni.showToast({
							title: "支付成功",
							icon: "none"
						});
						setTimeout(() => uni.reLaunch({
							url: "/pages/index/orderList"
						}), 1000);
					},
					fail: (err) => {
						console.error("支付失败：", err);
						uni.showToast({
							title: "支付失败",
							icon: "none"
						});
						setTimeout(() => {
							this.can = true;
							uni.reLaunch({
								url: "/pages/index/orderList"
							});
						}, 1500);
					}
				});
			},

			// 2. 配送类型切换
			changeType(type) {
				this.type = type;
			},

			// 3. 数据请求：获取自提点列表
			getlocationList() {
				this.$http.post("/app/dishs/locationList", {
					longitude: this.longitude,
					latitude: this.latitude,
					shop_id: this.shopData.id
				}).then(res => {
					if (res.code === 0) {
						this.cList = [...this.cList, ...res.data.list];
						// 初始化自提点（优先使用缓存，无则用第一个）
						if (this.cList.length > 0) {
							const cachedSendData = uni.getStorageSync("sendData") || {};
							const hasCached = this.cList.some(item => item.id === cachedSendData.id);
							this.sendData = hasCached ? cachedSendData : this.cList[0];
							uni.setStorageSync("sendData", this.sendData);
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none"
						});
					}
				}).catch(err => {
					console.error("获取自提点失败：", err);
				});
			}
		}
	};
</script>

<style lang="less" scoped>
	@color: #E51B00;

	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		/* 整体背景色 */

		/* 1. 顶部区域 */
		.co-top {
			border-radius: 20rpx;
			background-color: #efefef;
			overflow: hidden;

			/* 配送方式导航 */
			.nav {
				height: 80rpx;
				line-height: 80rpx;

				.i {
					flex: 1;
					text-align: center;
					background-color: #efefef;
					color: #7b7b7b;
					font-size: 30rpx;
				}

				.on1 {
					background-color: #fff;
					color: #000;
					font-weight: 600;
					border-radius: 20rpx 20rpx 0 0;
					position: relative;

					&::after {
						position: absolute;
						right: -20rpx;
						bottom: 0;
						background-color: #fff;
						width: 20rpx;
						height: 20rpx;
						content: '';
					}

					&::before {
						position: absolute;
						right: -40rpx;
						bottom: 0;
						background-color: #eee;
						width: 40rpx;
						height: 40rpx;
						border-radius: 20rpx;
						content: '';
						z-index: 100;
					}
				}

				.on2 {
					background-color: #fff;
					color: #000;
					font-weight: 600;
					border-radius: 20rpx 20rpx 0 0;
					position: relative;

					&::after {
						position: absolute;
						left: -20rpx;
						bottom: 0;
						background-color: #fff;
						width: 20rpx;
						height: 20rpx;
						content: '';
					}

					&::before {
						position: absolute;
						left: -40rpx;
						bottom: 0;
						background-color: #eee;
						width: 40rpx;
						height: 40rpx;
						border-radius: 20rpx;
						content: '';
						z-index: 100;
					}
				}
			}

			/* 店铺/自提点信息 */
			.shop {
				padding: 20rpx;
				background-color: #fff;
				border-radius: 0 0 20rpx 20rpx;
				margin-top: -1rpx;

				.l {
					flex: 1;
					width: 1rpx;

					.img {
						width: 80rpx;
						height: 80rpx;
						background: #fff;
						border-radius: 8rpx;
						border: 2rpx solid #000;
						overflow: hidden;
						box-sizing: border-box;
						padding: 2rpx;

						image {
							width: 100%;
							height: 100%;
						}
					}

					.con {
						flex: 1;
						width: 1px;
						margin-left: 15rpx;

						.name {
							line-height: 40rpx;
							height: 40rpx;
							font-size: 28rpx;
							color: #000;
						}

						.p {
							margin-top: 10rpx;
							line-height: 30rpx;
							font-size: 22rpx;
							color: #b1b1b1;
							text-align: left;
						}
					}
				}

				.r {
					width: 40rpx;
					height: 40rpx;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}
		}

		/* 2. 商品列表区域 */
		.list {
			padding-bottom: 120rpx;
			/* 预留底部按钮高度 */

			.item {
				padding: 20rpx;
				border-radius: 20rpx;
				margin-top: 20rpx;
				background-color: #fff;

				/* 日期和取餐时间 */
				.i-top {
					display: flex;
					align-items: center;

					image {
						width: 32rpx;
						height: 32rpx;
						margin-right: 10rpx;
					}

					.t1 {
						font-size: 32rpx;
						color: @color;
					}

					.t2 {
						font-size: 32rpx;
						color: #000;
						margin-left: 10rpx;
					}
				}

				/* 商品列表 */
				.i-list {
					.i-middle {
						border-bottom: 2rpx solid #eee;
						padding: 30rpx 0;

						.img {
							width: 100rpx;
							height: 100rpx;
							border-radius: 12rpx;
							overflow: hidden;

							image {
								width: 100%;
								height: 100%;
							}
						}

						.con {
							flex: 1;
							width: 1rpx;
							margin-left: 20rpx;
							margin-right: 20rpx;

							.name {
								height: 30rpx;
								line-height: 30rpx;
								font-size: 28rpx;
								color: #000;
								text-align: left;
							}

							.info {
								margin-top: 15rpx;

								.i {
									font-size: 24rpx;
									color: #b5b5bb;
									line-height: 40rpx;

									text {
										color: #e6a23c;
										margin-left: 6rpx;
										font-size: 20rpx;
									}
								}
							}
						}

						.r {
							.price {
								height: 40rpx;
								color: #000;
								font-size: 20rpx;

								text {
									font-size: 28rpx;
									font-weight: bold;
								}
							}

							.num {
								height: 40rpx;
								line-height: 40rpx;
								font-size: 28rpx;
								color: #7b7b7b;
								text-align: right;
							}
						}
					}
				}

				/* 小计 */
				.i-footer {
					text-align: right;
					height: 60rpx;
					line-height: 60rpx;
					font-size: 24rpx;
					color: #000;

					text {
						font-size: 32rpx;
						font-weight: 600;
					}
				}
			}
		}

		/* 3. 底部按钮区域 */
		.footer-btn {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			padding: 20rpx 20rpx 40rpx;
			background-color: #fff;
			z-index: 999;

			.l {
				flex: 1;
				width: 1rpx;
				margin-right: 20rpx;
				text-align: right;
				font-size: 28rpx;
				color: #000;

				text {
					font-size: 40rpx;
					font-weight: 600;
				}
			}

			.r {
				width: 220rpx;
				height: 80rpx;
				background: @color;
				color: #fff;
				border-radius: 40rpx;
				text-align: center;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				.t {
					height: 40rpx;
					line-height: 40rpx;
					font-size: 30rpx;
				}

				.p {
					height: 30rpx;
					line-height: 30rpx;
					font-size: 18rpx;
				}
			}
		}
	}
</style>